//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package data_anno_project_api_serv

import (
	"context"
	"strings"
	"time"

	"atomgit.com/openlinksaas/api-server/api_common"
	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/data_anno_dao"
	"atomgit.com/openlinksaas/api-server/dao/fs_dao"
	"atomgit.com/openlinksaas/api-server/dao/project_entry_dao"
	"atomgit.com/openlinksaas/api-server/utils"
	"atomgit.com/openlinksaas/proto-gen-go.git/data_anno_project_api"
	"atomgit.com/openlinksaas/proto-gen-go.git/project_entry_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

func (apiImpl *DataAnnoProjectApiImpl) AddResource(ctx context.Context, req *data_anno_project_api.AddResourceRequest) (*data_anno_project_api.AddResourceResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &data_anno_project_api.AddResourceResponse{
			Code:   data_anno_project_api.AddResourceResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	//检查权限
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &data_anno_project_api.AddResourceResponse{
			Code:   data_anno_project_api.AddResourceResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &data_anno_project_api.AddResourceResponse{
			Code:   data_anno_project_api.AddResourceResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}
	if projectItem.Closed {
		return &data_anno_project_api.AddResourceResponse{
			Code:   data_anno_project_api.AddResourceResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	entryItem, err := project_entry_dao.EntryDao.Get(ctx, req.AnnoProjectId, req.ProjectId)
	if err != nil {
		return &data_anno_project_api.AddResourceResponse{
			Code:   data_anno_project_api.AddResourceResponse_CODE_NO_ANNO_PROJECT,
			ErrMsg: "标注项目不存在",
		}, nil
	}
	if entryItem.EntryType != uint32(project_entry_api.ENTRY_TYPE_ENTRY_TYPE_DATA_ANNO) {
		return &data_anno_project_api.AddResourceResponse{
			Code:   data_anno_project_api.AddResourceResponse_CODE_NO_ANNO_PROJECT,
			ErrMsg: "标注项目不存在",
		}, nil
	}

	hasUpdatePerm := api_common.CheckEntryCanUpdate(sessionItem, projectItem, roleItem, entryItem)
	if !hasUpdatePerm {
		return &data_anno_project_api.AddResourceResponse{
			Code:   data_anno_project_api.AddResourceResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	//检查标注项目是否存在
	exist, err := data_anno_dao.AnnoProjectDao.Exist(ctx, req.ProjectId, req.AnnoProjectId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &data_anno_project_api.AddResourceResponse{
			Code:   data_anno_project_api.AddResourceResponse_CODE_NO_ANNO_PROJECT,
			ErrMsg: "标注项目不存在",
		}, nil
	}
	if req.StoreAsFile {
		exist, err = fs_dao.FsFileDao.Exist(ctx, projectItem.DataAnnoFsId, req.Content)
		if err != nil {
			return nil, err
		}
		if !exist {
			return &data_anno_project_api.AddResourceResponse{
				Code:   data_anno_project_api.AddResourceResponse_CODE_NO_FILE,
				ErrMsg: "文件不存在",
			}, nil
		}
	}

	resourceId := uuid.NewString()
	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = data_anno_dao.ResourceDao.Insert(sessCtx, &data_anno_dao.ResourceInfoDbItem{
			ResourceId:    resourceId,
			AnnoProjectId: req.AnnoProjectId,
			Content:       req.Content,
			StoreAsFile:   req.StoreAsFile,
			TimeStamp:     nowTime,
			TaskCount:     0,
		})
		if err != nil {
			return nil, err
		}
		// 更新资源数量
		count, err := data_anno_dao.ResourceDao.Count(sessCtx, req.AnnoProjectId)
		if err != nil {
			return nil, err
		}
		err = data_anno_dao.AnnoProjectDao.UpdateResourceCount(sessCtx, req.ProjectId, req.AnnoProjectId, count)
		if err != nil {
			return nil, err
		}
		return &data_anno_project_api.AddResourceResponse{
			Code:       data_anno_project_api.AddResourceResponse_CODE_OK,
			ResourceId: resourceId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*data_anno_project_api.AddResourceResponse), nil
}

func (apiImpl *DataAnnoProjectApiImpl) RemoveResource(ctx context.Context, req *data_anno_project_api.RemoveResourceRequest) (*data_anno_project_api.RemoveResourceResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &data_anno_project_api.RemoveResourceResponse{
			Code:   data_anno_project_api.RemoveResourceResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	//检查权限
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &data_anno_project_api.RemoveResourceResponse{
			Code:   data_anno_project_api.RemoveResourceResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &data_anno_project_api.RemoveResourceResponse{
			Code:   data_anno_project_api.RemoveResourceResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}
	if projectItem.Closed {
		return &data_anno_project_api.RemoveResourceResponse{
			Code:   data_anno_project_api.RemoveResourceResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	entryItem, err := project_entry_dao.EntryDao.Get(ctx, req.AnnoProjectId, req.ProjectId)
	if err != nil {
		return &data_anno_project_api.RemoveResourceResponse{
			Code:   data_anno_project_api.RemoveResourceResponse_CODE_NO_ANNO_PROJECT,
			ErrMsg: "标注项目不存在",
		}, nil
	}
	if entryItem.EntryType != uint32(project_entry_api.ENTRY_TYPE_ENTRY_TYPE_DATA_ANNO) {
		return &data_anno_project_api.RemoveResourceResponse{
			Code:   data_anno_project_api.RemoveResourceResponse_CODE_NO_ANNO_PROJECT,
			ErrMsg: "标注项目不存在",
		}, nil
	}

	hasUpdatePerm := api_common.CheckEntryCanUpdate(sessionItem, projectItem, roleItem, entryItem)
	if !hasUpdatePerm {
		return &data_anno_project_api.RemoveResourceResponse{
			Code:   data_anno_project_api.RemoveResourceResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	//检查标注项目是否存在
	exist, err := data_anno_dao.AnnoProjectDao.Exist(ctx, req.ProjectId, req.AnnoProjectId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &data_anno_project_api.RemoveResourceResponse{
			Code:   data_anno_project_api.RemoveResourceResponse_CODE_NO_ANNO_PROJECT,
			ErrMsg: "标注项目不存在",
		}, nil
	}

	//检查资源是否存在
	exist, err = data_anno_dao.ResourceDao.Exist(ctx, req.ResourceId, req.AnnoProjectId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &data_anno_project_api.RemoveResourceResponse{
			Code:   data_anno_project_api.RemoveResourceResponse_CODE_NO_RESOURCE,
			ErrMsg: "标注资源不存在",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = data_anno_dao.ResourceDao.Remove(sessCtx, req.ResourceId, req.AnnoProjectId)
		if err != nil {
			return nil, err
		}
		//更新资源数量
		count, err := data_anno_dao.ResourceDao.Count(sessCtx, req.AnnoProjectId)
		if err != nil {
			return nil, err
		}
		err = data_anno_dao.AnnoProjectDao.UpdateResourceCount(sessCtx, req.ProjectId, req.AnnoProjectId, count)
		if err != nil {
			return nil, err
		}
		//删除任务和结果
		memberUserIdList, err := data_anno_dao.AnnoTaskDao.DistinctMemberByResource(sessCtx, req.AnnoProjectId, req.ResourceId)
		if err != nil {
			return nil, err
		}
		err = data_anno_dao.AnnoTaskDao.RemoveByResource(sessCtx, req.AnnoProjectId, req.ResourceId)
		if err != nil {
			return nil, err
		}
		err = data_anno_dao.AnnoResultDao.RemoveByResource(sessCtx, req.AnnoProjectId, req.ResourceId)
		if err != nil {
			return nil, err
		}
		//调整成员内任务计数器
		for _, memberUserId := range memberUserIdList {
			count, err = data_anno_dao.AnnoTaskDao.CountByMember(sessCtx, req.AnnoProjectId, memberUserId, false, false)
			if err != nil {
				return nil, err
			}
			err = data_anno_dao.AnnoMemberDao.UpdateTaskCount(sessCtx, req.AnnoProjectId, memberUserId, count)
			if err != nil {
				return nil, err
			}
			count, err = data_anno_dao.AnnoTaskDao.CountByMember(sessCtx, req.AnnoProjectId, memberUserId, true, true)
			if err != nil {
				return nil, err
			}
			err = data_anno_dao.AnnoMemberDao.UpdateDoneCount(sessCtx, req.AnnoProjectId, memberUserId, count)
			if err != nil {
				return nil, err
			}
		}
		//调整项目任务计数器
		count, err = data_anno_dao.AnnoTaskDao.CountByAnnoProject(sessCtx, req.AnnoProjectId, false, false)
		if err != nil {
			return nil, err
		}
		err = data_anno_dao.AnnoProjectDao.UpdateAllTaskCount(sessCtx, req.ProjectId, req.AnnoProjectId, count)
		if err != nil {
			return nil, err
		}
		count, err = data_anno_dao.AnnoTaskDao.CountByAnnoProject(sessCtx, req.AnnoProjectId, true, true)
		if err != nil {
			return nil, err
		}
		err = data_anno_dao.AnnoProjectDao.UpdateDoneTaskCount(sessCtx, req.ProjectId, req.AnnoProjectId, count)
		if err != nil {
			return nil, err
		}

		return &data_anno_project_api.RemoveResourceResponse{
			Code: data_anno_project_api.RemoveResourceResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*data_anno_project_api.RemoveResourceResponse), nil
}

func (apiImpl *DataAnnoProjectApiImpl) ListResource(ctx context.Context, req *data_anno_project_api.ListResourceRequest) (*data_anno_project_api.ListResourceResponse, error) {
	emptyList := []*data_anno_project_api.ResourceInfo{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &data_anno_project_api.ListResourceResponse{
			Code:     data_anno_project_api.ListResourceResponse_CODE_WRONG_SESSION,
			ErrMsg:   "会话不存在",
			InfoList: emptyList,
		}, nil
	}
	//检查权限
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &data_anno_project_api.ListResourceResponse{
			Code:     data_anno_project_api.ListResourceResponse_CODE_NO_PROJECT,
			ErrMsg:   "项目不存在",
			InfoList: emptyList,
		}, nil
	} else if err == utils.ErrNoRole {
		return &data_anno_project_api.ListResourceResponse{
			Code:     data_anno_project_api.ListResourceResponse_CODE_NO_PERMISSION,
			ErrMsg:   "没有权限",
			InfoList: emptyList,
		}, nil
	} else if err != nil {
		return nil, err
	}
	if projectItem.Closed {
		return &data_anno_project_api.ListResourceResponse{
			Code:     data_anno_project_api.ListResourceResponse_CODE_NO_PERMISSION,
			ErrMsg:   "没有权限",
			InfoList: emptyList,
		}, nil
	}

	entryItem, err := project_entry_dao.EntryDao.Get(ctx, req.AnnoProjectId, req.ProjectId)
	if err != nil {
		return &data_anno_project_api.ListResourceResponse{
			Code:     data_anno_project_api.ListResourceResponse_CODE_NO_ANNO_PROJECT,
			ErrMsg:   "标注项目不存在",
			InfoList: emptyList,
		}, nil
	}
	if entryItem.EntryType != uint32(project_entry_api.ENTRY_TYPE_ENTRY_TYPE_DATA_ANNO) {
		return &data_anno_project_api.ListResourceResponse{
			Code:     data_anno_project_api.ListResourceResponse_CODE_NO_ANNO_PROJECT,
			ErrMsg:   "标注项目不存在",
			InfoList: emptyList,
		}, nil
	}

	hasUpdatePerm := api_common.CheckEntryCanUpdate(sessionItem, projectItem, roleItem, entryItem)
	if !hasUpdatePerm {
		return &data_anno_project_api.ListResourceResponse{
			Code:     data_anno_project_api.ListResourceResponse_CODE_NO_PERMISSION,
			ErrMsg:   "没有权限",
			InfoList: emptyList,
		}, nil
	}

	//检查标注项目是否存在
	exist, err := data_anno_dao.AnnoProjectDao.Exist(ctx, req.ProjectId, req.AnnoProjectId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &data_anno_project_api.ListResourceResponse{
			Code:     data_anno_project_api.ListResourceResponse_CODE_NO_ANNO_PROJECT,
			ErrMsg:   "标注项目不存在",
			InfoList: emptyList,
		}, nil
	}

	count, err := data_anno_dao.ResourceDao.Count(ctx, req.AnnoProjectId)
	if err != nil {
		return nil, err
	}
	resourceItemList, err := data_anno_dao.ResourceDao.List(ctx, req.AnnoProjectId, int64(req.Offset), int64(req.Limit))
	if err != nil {
		return nil, err
	}
	//计算文件结尾
	fileIdList := []string{}
	for _, resourceItem := range resourceItemList {
		if resourceItem.StoreAsFile {
			fileIdList = append(fileIdList, resourceItem.Content)
		}
	}
	fileItemList, err := fs_dao.FsFileDao.ListById(ctx, projectItem.DataAnnoFsId, fileIdList)
	if err != nil {
		return nil, err
	}
	fileExtMap := map[string]string{}
	for _, fileItem := range fileItemList {
		pos := strings.LastIndex(fileItem.FileName, ".")
		if pos != -1 {
			fileExtMap[fileItem.FileId] = fileItem.FileName[pos+1:]
		}
	}

	infoList := []*data_anno_project_api.ResourceInfo{}
	for _, resourceItem := range resourceItemList {
		info := resourceItem.ToResourceInfo()
		if resourceItem.StoreAsFile {
			info.FileExt = fileExtMap[resourceItem.Content]
		}
		infoList = append(infoList, info)
	}
	return &data_anno_project_api.ListResourceResponse{
		Code:       data_anno_project_api.ListResourceResponse_CODE_OK,
		TotalCount: count,
		InfoList:   infoList,
	}, nil
}
